package cn.ryh.netty.nio.groupchat;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;

/**
 * 群聊服务端
 *
 * @author Raoyh
 * @Description
 * @create 2022-09-13 10:41
 */
public class Server {
    public static void main(String[] args) {
        Server server = new Server();
        server.listen();
    }

    /**
     * 定义属性
     */
    private Selector selector;
    private ServerSocketChannel listenChannel;

    private static final int PORT = 6667;

    /**
     * 构造器
     * 初始化工作
     */
    public Server() {
        try {
            //得到选择器
            selector = Selector.open();
            //ServerSocketChannel
            listenChannel = ServerSocketChannel.open();
            //绑定端口
            listenChannel.socket().bind(new InetSocketAddress(PORT));
            //设置非阻塞模式
            listenChannel.configureBlocking(false);
            //将该 listenChannel 注册到 selector,用于监听连接注册事件
            listenChannel.register(selector, SelectionKey.OP_ACCEPT);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void listen() {
        try {
            while (true) {
                //监控所有注册的通道，当其有IO操作可以进行时，将对应的SelectionKey加入到内部集合中，参数用来设置超时时间
                int count = selector.select();
                // 有事件处理
                if (count > 0) {
                    // 遍历得到 selectedKeys(关注事件) 集合
                    Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
                    while (iterator.hasNext()) {
                        SelectionKey key = iterator.next();
                        // 监听到accept 事件
                        if (key.isAcceptable()) {
                            // 获取客户端连接注册过来的通道
                            SocketChannel socketChannel = listenChannel.accept();
                            //设置非阻塞模式
                            socketChannel.configureBlocking(false);
                            //将该 socketChannel 注册到 selector， 将其也注册到 selector 中便于管理
                            socketChannel.register(selector, SelectionKey.OP_READ);
                            //提示
                            String msg = socketChannel.getRemoteAddress() + " 上线 ";
                            System.out.println(msg);
                            sendInfoToOtherClients(msg, socketChannel);
                        }
                        // 监听到 read事件，即通道是可读的状态
                        if (key.isReadable()) {
                            readData(key);
                        }
                        //当前的 key 删除，防止重复处理
                        iterator.remove();
                    }
                } else {
                    System.out.println("等待....");
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void readData(SelectionKey key) {
        SocketChannel socketChannel = null;
        try {
            socketChannel = (SocketChannel) key.channel();
            ByteBuffer buf = ByteBuffer.allocate(1024);
            int read = socketChannel.read(buf);
            if (read > 0) {
                String msg = new String(buf.array());
                System.out.println("form 客户端：" + msg);
                // 向其他客户端转发消息去掉自己
                sendInfoToOtherClients(msg, socketChannel);
            }
        } catch (IOException e) {
            try {
                System.out.println(socketChannel.getRemoteAddress() + ": 离线了");
                key.cancel();
                socketChannel.close();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }

    private void sendInfoToOtherClients(String msg, SocketChannel socketChannel) throws IOException {
        System.out.println("转发消息中。。。。。。");
        for (SelectionKey key : selector.keys()) {
            Channel channel = key.channel();
            if (channel instanceof SocketChannel && channel != socketChannel) {
                SocketChannel temp = (SocketChannel) channel;
                temp.write(ByteBuffer.wrap(msg.getBytes()));
            }
        }
    }
}
